package Year22_Month06.day18;

public class 最大二叉树 {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return rebuildTree(nums,0,nums.length);
    }

    public TreeNode rebuildTree(int[] arr,int left,int right){
        if(left == right) return null;
        int max = Integer.MIN_VALUE;
        int maxindex = left;
        int index = left;
        while (index < right){
            if(arr[index] > max) {
                max = arr[index];
                maxindex = index;
            }
            index++;
        }
        TreeNode node = new TreeNode(max);
        node.left = rebuildTree(arr,left,maxindex);
        node.right = rebuildTree(arr,maxindex+1,right);
        return node;
    }

//    public TreeNode rebuildTree(int[] arr,int left,int right){
//        if(left == right) return null;
//        int max = Integer.MIN_VALUE;
//        int index = left;
//        for (int i = left; i < right; i++) {
//            if(arr[i] > max){
//                max = arr[i];
//                index = i;
//            }
//        }
//        TreeNode node = new TreeNode(max);
//        node.left = rebuildTree(arr,left,index);
//        node.right = rebuildTree(arr,index+1,right);
//        return node;
//    }
}
